package com.maduar.demo;

import com.maduar.demo.util.ErrorInfo;
import com.maduar.demo.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;

/**
 * Description:
 *
 * @author danny.pang danny.pang@ebizprise.com
 * @date 2020-05-09 23:03
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * ValidationException
     */
    @ExceptionHandler(ValidationException.class)
    public Result handleValidationException(ValidationException e) {
        log.error(e.getMessage(), e);
        return Result.error(ErrorInfo.illegalParameter(e.getCause().getMessage()));
    }

    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        return Result.error(ErrorInfo.illegalParameter(e.getBindingResult().getFieldError().getDefaultMessage()));
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return Result.error(ErrorInfo.serviceError("404,路径错误"));
    }

    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(Throwable.class)
    public Result handlerThrowable(Throwable e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        return Result.error(ErrorInfo.serviceError("系统繁忙,请稍后再试"));
    }

}
